import contextvars
import asyncio

# 创建一个上下文变量
user_info = contextvars.ContextVar('user_info', default="Unknown")

async def task1():
    # 设置上下文变量
    user_info.set("Alice")
    print(f"Task 1: User is {user_info.get()}")
    await asyncio.sleep(1)
    print(f"Task 1 after sleep: User is still {user_info.get()}")

async def task2():
    # 设置上下文变量
    user_info.set("Bob")
    print(f"Task 2: User is {user_info.get()}")
    await asyncio.sleep(1)
    print(f"Task 2 after sleep: User is still {user_info.get()}")

async def main():
    await asyncio.gather(task1(), task2())

# 运行任务
asyncio.run(main())